package com.jy.adscm.hcPlan.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.jy.adscm.exception.AdscmSystemException;
import com.jy.adscm.hcPlan.bean.*;
import com.jy.adscm.hcPlan.bean.develop2.HcPlanZjkMiddlelibrary;
import com.jy.adscm.hcPlan.bean.support.HcPlanMakePartExampleSopport;
import com.jy.adscm.hcPlan.bean.support.HcPlanMakePartMergeSupport;
import com.jy.adscm.hcPlan.mapper.mysql.*;
import com.jy.adscm.hcPlan.mapper.mysqlFollower.MySqlFollowerMapper;
import com.jy.adscm.hcPlan.service.HcPlanMakePartExampleService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.jy.adscm.utils.AdscmBaseUtils;
import com.jy.adscm.utils.AdscmDateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 单批次耗材零件制造配置 服务实现类
 * </p>
 *
 * @author yyy
 * @since 2018-08-15
 */
@Service("hcPlanMakePartExampleService")
public class HcPlanMakePartExampleServiceImpl extends ServiceImpl<HcPlanMakePartExampleMapper, HcPlanMakePartExample> implements HcPlanMakePartExampleService {
    Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    HcPlanMakePartExampleMapper hcPlanMakePartExampleMapper;
    @Autowired
    HcPlanFinalAssemblyMapper hcPlanFinalAssemblyMapper;
    @Autowired
    HcPlanMakePartMapper hcPlanMakePartMapper;
    @Autowired
    HcPlanSaleMapper hcPlanSaleMapper;
    @Autowired
    HcPlanMachineMapper hcPlanMachineMapper;
    @Autowired
    HcPlanLjzzPartsmadeMapper ljzzPartsmadeMapper;
    @Autowired
    HcPlanMakePartMaterielExampleMapper hcPlanMakePartMaterielExampleMapper;
    @Autowired
    MySqlFollowerMapper mySqlFollowerMapper;
    @Autowired
    HcPlanZjkMiddlelibraryMapper zjkMiddlelibraryMapper;

    @Override
    public Map<String, List<HcPlanMakePartExample>> getHcPartExamples(String date) throws AdscmSystemException {

        logger.info("以零件的制造机器为key，获取所有需要由这个机器制造的零件的相关信息...");

        try{
            Map<String, List<HcPlanMakePartExample>> map = new HashMap<>();

            String startTime = date + "-01 00:00:00";
            Date endDate = AdscmDateUtils.getLastDayOfTheMonth(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(startTime));
            String endTime = AdscmDateUtils.getDateFomat(AdscmDateUtils.getThatDateTime(endDate));

            List<HcPlanMakePartExample> list = hcPlanMakePartExampleMapper.getAssemblyPartExamples(startTime,endTime);

            Map<String, Object> userMap = new HashMap<>();
            List<Map<String, Object>> users = mySqlFollowerMapper.getAllMakeUser();
            if (users != null && users.size()>0){
                for (Map<String, Object> maps :
                        users) {
                    userMap.put((String )maps.get("PERSONID"),maps.get("PERSONNAME"));
                }
            }

            if (list != null && list.size() > 0){
                for (HcPlanMakePartExample example :
                        list) {

                    Object operator = userMap.get(example.getOperator());
                    if (operator != null && operator instanceof String){
                        example.setOperator((String)operator);
                    }

                    String macCode = example.getMake_machine();
                    if (macCode != null){
                        List<HcPlanMakePartExample> exampleList = map.get(macCode);
                        if (exampleList == null){
                            exampleList = new ArrayList<>();
                            map.put(macCode,exampleList);
                        }
                        exampleList.add(example);
                    }

                }
            }
            return map;
        }catch (Exception e){
            logger.error("查询零件制造列表异常",e);
            throw new AdscmSystemException(e.getMessage());
        }
    }

    @Transactional
    @Override
    public void editAllHcPartExamples(HcPlanMakePartExample example) throws AdscmSystemException {
        logger.info("修改零件的制作机器...");
        try{

            hcPlanMakePartExampleMapper.updateById(example);

        }catch (Exception e){
            logger.error("修改零件的制作机器异常",e);
            throw new AdscmSystemException(e.getMessage());
        }


    }
    @Transactional
    @Override
    public String  mergePart(String start_date,String end_date,String  macCode,String operator,List<Long> ids,String isUpdate)  throws AdscmSystemException {
        logger.info("开始并单【"+ids+"】...");
        try {

            if (AdscmDateUtils.parseDate(start_date).getTime() < new Date().getTime()){
                throw new AdscmSystemException("并单的开始时间小于了当前时间，不能并单");
            }

            String mergeId = null;
            if (ids != null && ids.size()>0){

                //获取选择的这一批订单他们的最早的那个总装的开始时间
                List<Long> assemblyIds = hcPlanMakePartExampleMapper.getAllAssemblyIds(ids);
                Date minAssemblyStartDate = hcPlanFinalAssemblyMapper.getMinAssemblyStartDate(assemblyIds);

                if (minAssemblyStartDate == null){
                    throw new AdscmSystemException("没有找到总装的时间");
                }else{
                    Date endDate = AdscmDateUtils.parseDate(end_date);
                    if (endDate.getTime() > minAssemblyStartDate.getTime()){
                        throw new AdscmSystemException("并单的时间超过了总装的最早期限，不能并单");
                    }
                }


                List<HcPlanMakePartExample> partExamples = hcPlanMakePartExampleMapper.selectBatchIds(ids);
                if (partExamples != null && partExamples.size()>0){
                    //获取当前机器制造的最晚时间
//                    Date maxEndTime = hcPlanMakePartExampleMapper.getMaxEndTime(partExamples.get(0).getMake_machine());
//                    if (maxEndTime != null){
//                        if (AdscmDateUtils.parseDate(start_date).getTime() < maxEndTime.getTime()){
//                            throw new AdscmSystemException("并单的开始时间小于了这台机器的最晚生产制造时间，不能并单");
//                        }
//                    }

                    Integer merge_sort_num = null;
                    if (!"1".equals(isUpdate)){
                        mergeId = AdscmDateUtils.getNowOnlyDateFomat2(new Date());
                        merge_sort_num = hcPlanMakePartExampleMapper.getMaxMergeSortNum(mergeId);
                        if (merge_sort_num == null){
                            merge_sort_num = 1;
                        }else {
                            merge_sort_num += 1;
                        }
                        String result = AdscmBaseUtils.getInstance().addZeroToStr(merge_sort_num.toString(),3,"0");
                        mergeId += result;
                    }

                    for (HcPlanMakePartExample example:
                         partExamples) {

                        if (!"1".equals(isUpdate)){
                            example.setMerge_id(mergeId);
                            example.setMerge_sort_num(merge_sort_num);
                        }else {
                            if (mergeId == null){
                                mergeId = example.getMerge_id();
                            }
                        }
                        example.setMake_start_time(AdscmDateUtils.parseDate(start_date));
                        example.setMake_end_time(AdscmDateUtils.parseDate(end_date));
                        example.setMake_machine(macCode);
                        example.setOperator(operator);
                        example.setPart_make_status(1);

                        hcPlanMakePartExampleMapper.updateById(example);

                        //修改物料采购记录中的零件信息
                        HcPlanMakePartMaterielExample pme = new HcPlanMakePartMaterielExample();
                        pme.setAssembly_id(example.getAssembly_id());
                        pme.setPart_id(example.getPart_id());
                        pme = hcPlanMakePartMaterielExampleMapper.selectOne(pme);

                        if (AdscmBaseUtils.getInstance().isNotEmpty(pme,"id")){
                            pme.setPart_merge_id(mergeId);
                            pme.setMake_start_time(AdscmDateUtils.parseDate(start_date));
                            pme.setMake_end_time(AdscmDateUtils.parseDate(end_date));
                            hcPlanMakePartMaterielExampleMapper.updateById(pme);
                        }

                    }


                }else {
                    throw new AdscmSystemException("没有查询到【"+ids+"】需要并单的零件集合，并单失败");
                }

            }else {
                throw new AdscmSystemException("没有获取到需要并单的零件集合，并单失败");
            }
            return mergeId;

        }catch (Exception e){
            logger.error("零件制造并单【"+ids+"】异常",e);
            throw new AdscmSystemException(e.getMessage());
        }
    }

    //    @Transactional
//    @Override
    public void loadHcPartExampleByAssemblyId(Long assemblyId) throws AdscmSystemException {
        logger.info("装配单批次零件制造的数据，总装id【"+assemblyId+"】...");
        try{

            HcPlanFinalAssembly assembly = hcPlanFinalAssemblyMapper.selectById(assemblyId);
            if (AdscmBaseUtils.getInstance().isNotEmpty(assembly,"id")){
                List<HcPlanMakePart> partList = hcPlanMakePartMapper.selectList(null);//所有零件的标准配置
                Integer productionTime = hcPlanMakePartMapper.getProductionTime();//每天的标准生产时间
                if (partList != null && partList.size()>0){
//                    Map<String,Object> conditionMap = new HashMap<>();
//                    conditionMap.put("assembly_id",assembly.getId());
//                    Wrapper wrapper = new EntityWrapper();
//                    wrapper.where("assembly_id = ?",assembly.getId());
//                    Integer count = hcPlanMakePartExampleMapper.selectCount(wrapper);

                    Map<Integer,Date> minDateMap = new HashMap<>();//记录这个总装批次对应的零件制造机器的最靠前的时间

                    for (HcPlanMakePart part :
                            partList) {
                        HcPlanMakePartExample example = new HcPlanMakePartExample();
                        example.setPart_id(part.getId());
                        example.setAssembly_id(assembly.getId());
                        example = hcPlanMakePartExampleMapper.selectOne(example);

                        boolean isUpdate = false;
                        if (AdscmBaseUtils.getInstance().isNotEmpty(example,"id")){
                            //更新
                            isUpdate = true;
                        }else {
                            //增加
                            example = new HcPlanMakePartExample();
                            example.setPart_id(part.getId());
                            example.setPart_name(part.getPart_name());
                            example.setAssembly_id(assembly.getId());
                            example.setPart_make_status(0);
                        }
//                        example.setMake_cycle_hour(part.getA_batch_make_cycle_hour());//制造周期
                        //制造机器
//                        HcPlanMachine machine = hcPlanMachineMapper.selectById(part.getMake_machine_id());
//                        example.setMake_machine(machine.getMacCode());
                        example.setMake_machine(part.getMake_machine_name());
                        //制造开始时间
                        //制造结束时间【结束时间应该在总装开始之前，默认为总装开始日期0点前】
                        Date minDate = minDateMap.get(part.getMake_machine_id());
                        Date makeStartTime = null;
                        Date makeEndTime = null;
//                        int md_1 =  part.getMake_cycle_hour() % productionTime;
                        int md = 0;
//                        if(part.getMake_cycle_hour() % productionTime == 0){
//                            md = -1;
//                        }
//                        md += part.getMake_cycle_hour() / productionTime;
//                        if (md_1 > 0){
//                            md += 1;
//                        }

                        if (minDate == null){
                            Date assStartDate = assembly.getAss_start_date();//总装开始时间

                            //零件制造完成就需要在总装开始时间前一天
                            makeEndTime = AdscmDateUtils.getThatDate(assStartDate,-1,Calendar.DATE);

                            makeStartTime = AdscmDateUtils.getThatDate(makeEndTime,AdscmBaseUtils.getInstance().getOppositeNum(md),Calendar.DATE);

                            //在总装开始时间的基础上，减去制造的周期，就是制造开始时间
//                            makeStartTime = AdscmDateUtils.getThatDate(assStartDate,AdscmBaseUtils.getInstance().getOppositeNum(part.getMake_cycle_hour()),Calendar.HOUR);


                            example.setMake_end_time(AdscmDateUtils.getThatDateTime(makeEndTime));
                            example.setMake_start_time(makeStartTime);
//                            makeStartTime = AdscmDateUtils.getThatDate(makeStartTime,-1,Calendar.DATE);
//                            minDateMap.put(part.getMake_machine(),makeStartTime);//将最新的总装开始时间放进去，如果有下一个，就把这个作为结束时间
                        }else{

                            example.setMake_end_time(AdscmDateUtils.getThatDateTime(minDate));
                            makeStartTime = AdscmDateUtils.getThatDate(minDate,AdscmBaseUtils.getInstance().getOppositeNum(md),Calendar.DATE);//AdscmDateUtils.getThatDate(minDate,AdscmBaseUtils.getInstance().getOppositeNum(part.getMake_cycle_hour()),Calendar.HOUR);
                            example.setMake_start_time(makeStartTime);
                        }

                        makeStartTime = AdscmDateUtils.getThatDate(makeStartTime,-1,Calendar.DATE);
                        minDateMap.put(part.getMake_machine_id(),makeStartTime);//将最新的总装开始时间放进去，如果有下一个，就把这个作为结束时间

                        if (isUpdate){
                            hcPlanMakePartExampleMapper.updateById(example);
                        }else {
                            hcPlanMakePartExampleMapper.insert(example);
                        }


                    }
                }
            }

        }catch (Exception e){
            logger.error("装配单批次零件制造的数据，总装id【"+assemblyId+"】异常",e);
            throw new AdscmSystemException(e.getMessage());
        }
    }

    @Override
    public void loadHcPartExampleByAssemblyId_new1(Long assemblyId) throws AdscmSystemException {
        logger.info("装配指定总装批次对应的零件制造的数据，总装id【"+assemblyId+"】...");

        try {

            HcPlanFinalAssembly assembly = hcPlanFinalAssemblyMapper.selectById(assemblyId);//获取总装数据
            if (AdscmBaseUtils.getInstance().isNotEmpty(assembly,"id")){
                List<HcPlanMakePart> partList = hcPlanMakePartMapper.selectList(null);//所有零件的标准配置
                if (partList != null && partList.size()>0){
                    for (HcPlanMakePart part :
                            partList) {
                        HcPlanMakePartExample example = new HcPlanMakePartExample();
                        example.setPart_id(part.getId());
                        example.setAssembly_id(assembly.getId());
                        example = hcPlanMakePartExampleMapper.selectOne(example);

                        if (!AdscmBaseUtils.getInstance().isNotEmpty(example, "id")) {
                            //增加
                            example = new HcPlanMakePartExample();
                            example.setPart_id(part.getId());
                            example.setPart_name(part.getPart_name());
                            example.setAssembly_id(assembly.getId());
                            example.setPart_make_status(0);
                            example.setMake_machine(part.getMake_machine_name());

                            //获取客户信息
                            String customerCode = hcPlanSaleMapper.getCustomerCode(assembly.getSale_task_flow_num());

                            if (customerCode.startsWith("XLZ")){
                                //兰生的，G
                                example.setGoods_type("G型");
                                example.setMake_total_num(part.getG_batch_num());
                                example.setMake_cycle_hour(part.getG_batch_make_cycle_hour());
                            }else if(customerCode.startsWith("XRS")){
                                //蓉生的，A
                                example.setGoods_type("A型");
                                example.setMake_total_num(part.getA_batch_num());
                                example.setMake_cycle_hour(part.getA_batch_make_cycle_hour());
                            }
                            hcPlanMakePartExampleMapper.insert(example);
                        }
                    }
                }



            }


        }catch (Exception e){
            logger.error("装配指定总装批次对应的零件制造的数据，总装id【"+assemblyId+"】异常",e);
            throw new AdscmSystemException(e.getMessage());
        }


    }

    @Override
    public List<Map<String, Object>> getAllMakePartExample() throws AdscmSystemException {

        List<Map<String, Object>> list = null;

        logger.info("获取所有正在进行中的零件制造记录...");
        try{

            List<HcPlanMakePartExampleSopport> partExamples = hcPlanMakePartMapper.getFinalPartExample(null);

            if (partExamples != null && partExamples.size()>0){

                list = new ArrayList<>();

                for (HcPlanMakePartExampleSopport example : partExamples){
                    Map<String, Object> map = new HashMap<>();
                    map.put("id",example.getAssembly_id());
                    map.put("ass_start_date",example.getAss_start_date());
                    map.put("ass_end_date",example.getAss_end_date());

                    HcPlanFinalAssembly assembly = hcPlanFinalAssemblyMapper.selectById(example.getAssembly_id());
                    HcPlanSale planSale = hcPlanSaleMapper.getPlanSale(assembly.getSale_task_flow_num(), assembly.getGoods_id());

                    map.put("ass_cycle_day",assembly.getAss_cycle_day());
                    map.put("sale_task_flow_num",assembly.getSale_task_flow_num());
                    map.put("goods_id",assembly.getGoods_id());
                    map.put("final_ass_status",assembly.getFinal_ass_status());
                    map.put("goods_name",planSale.getGoods_name());
                    map.put("goods_model",planSale.getGoods_model());
                    map.put("customer_msg",planSale.getCustomer_msg());
                    map.put("plan_arrived_time",planSale.getPlan_arrived_time());


                    List<HcPlanMakePartExample> examples = example.getPartExamples();

                    if (examples != null && examples.size()>0){
                        for(int i=1;i<=examples.size();i++){

                            HcPlanMakePartExample ex = examples.get(i-1);
                            map.put("part"+i,ex);
                        }
                    }

                    list.add(map);

                }
            }


        }catch (Exception e){
            logger.error("获取所有正在进行中的零件制造记录异常",e);
            throw new AdscmSystemException(e.getMessage());
        }
        return list;
    }


    @Override
    public List<Map<String, Object>> getAllMakeUser() throws AdscmSystemException {
        List<Map<String, Object>> list = null;

        logger.info("获取所有获取所有生产二部的员工...");
        try{

            list = mySqlFollowerMapper.getAllMakeUser();

        }catch (Exception e){
            logger.error("获取获取所有生产二部的员工异常",e);
            throw new AdscmSystemException(e.getMessage());
        }
        return list;
    }

    @Override
    public HcPlanMakePartMergeSupport  getMergePartDetail(String mergeId) throws AdscmSystemException {

        logger.info("根据并单号["+mergeId+"]，获取并单详情...");
        try{

            return hcPlanMakePartExampleMapper.getMergePartDetail(mergeId);

        }catch (Exception e){
            logger.error("根据并单号["+mergeId+"]，获取并单详情.异常",e);
            throw new AdscmSystemException(e.getMessage());
        }
    }

    @Override
    public void submitMakePartTask(String merge_id) throws AdscmSystemException{
        logger.info("下发["+merge_id+"]零件制造任务...");
        try{

            //修改任务下发状态
            Wrapper<HcPlanMakePartExample> wrapper = new EntityWrapper<>();
            wrapper.eq("merge_id",merge_id);

            List<HcPlanMakePartExample> examples = hcPlanMakePartExampleMapper.selectList(wrapper);

            String partName = null;
            String macName = null;
            String operator = null;
            Date startTime = null;
            Date endTime = null;
            Integer totalNum = null;
            if (examples != null && examples.size()>0){
                for (HcPlanMakePartExample example :
                        examples) {
                    example.setPart_make_status(2);
                    if (partName == null){
                        partName = example.getPart_name();
                        macName = example.getMake_machine();
                        startTime = example.getMake_start_time();
                        endTime = example.getMake_end_time();
                        totalNum =  (int)(example.getMake_total_num() + 0.5);
                        operator = example.getOperator();
                    }
                    hcPlanMakePartExampleMapper.updateById(example);
                }
            }
            SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmssms");
            HcPlanLjzzPartsmade pm = new HcPlanLjzzPartsmade();
            pm.setTid(UUID.randomUUID().toString());
            pm.setTaskcode(Long.parseLong(format.format(new Date())));//任务流水号
            pm.setBatchnums(AdscmDateUtils.getNowOnlyDateFomat3(endTime) + "-1");//零件批号  //需要修改
            pm.setResourcename(partName);//零件名称
            pm.setTypenums(macName);//设备编号
            pm.setBusinesstype("注塑");//业务类型：注塑、吹塑、挤塑   //需要改动
            pm.setTaskreleaseperson("f0912aff-1076-4a92-bdd1-652f60e2e757");//文芳 ：零件制造计划编制人
            pm.setTaskperformperson(operator);//操作者
            pm.setTaskreleaseaddtime(new Date());//计划创建时间
            pm.setTaskstartorendtime(startTime);//生产计划开始时间
            pm.setTasknums(totalNum);//计划生产数量

            pm.setIstaskstart(0);
            pm.setIstaskbegin(0);
            pm.setIstaskend(0);
            pm.setIsreviewtask(0);
            pm.setTaskstate(0);
            pm.setTaskfinishstate(0);



            //生成零件制造待办任务
            ljzzPartsmadeMapper.insert(pm);

            //生成中间库待办任务
            HcPlanZjkMiddlelibrary zjk = new HcPlanZjkMiddlelibrary();
            zjk.setTid(UUID.randomUUID().toString());
            zjk.setTaskcode(Long.parseLong(format.format(new Date())));
            zjk.setBatchnums(pm.getBatchnums() + "-1");
            zjk.setResourcename(pm.getResourcename());
//            zjk.setTypenums(zzfa.getTypenums());
            zjk.setBusinesstype("入库");
            zjk.setTaskreleaseperson("f0912aff-1076-4a92-bdd1-652f60e2e757");
            zjk.setTaskreleaseaddtime(new Date());
            zjk.setTaskperformperson("de65dd3a-fc8a-471a-be30-89da9cb95b91");
            zjk.setTasktype(1);
            zjk.setIstaskstart(0);
            zjk.setIstaskbegin(0);
            zjk.setTasknums(totalNum+"");
            zjk.setIstaskend(0);
            zjk.setIsreviewtask(0);
            zjk.setTaskstate(0);
            zjk.setTaskfinishstate(0);
            zjkMiddlelibraryMapper.insert(zjk);


        }catch (Exception e){
            logger.error("下发["+merge_id+"]零件制造任务异常",e);
            throw new AdscmSystemException(e.getMessage());
        }
    }

    @Override
    public Map<String, Object> calculateMakePartTime_1(Long[] ids) throws AdscmSystemException {
        logger.info("程序自动计算，选择的一批待并单的零件的 生产时间...");
        try{
            Map<String, Object> map = new HashMap<>();
            if (ids != null && ids.length >0 ){
                List<HcPlanMakePartExample> examples = hcPlanMakePartExampleMapper.selectBatchIds(Arrays.asList(ids));//所有选择的待并单的零件

                Float cycle_hour = 0f;//花费时间
                String make_machine = null;//制造机器
                Float make_total_num = 0f;//制造总数

                Date startDate = null;//开始时间
                Date endDate = null;//结束时间

                List<Long> assemblyIds = new ArrayList<>();//所有总装ID集合

                for (HcPlanMakePartExample pe :
                        examples) {
                    if (make_machine == null){
                        make_machine = pe.getMake_machine();
                    }
                    cycle_hour += pe.getMake_cycle_hour();
                    make_total_num += pe.getMake_total_num();

                    assemblyIds.add(pe.getAssembly_id());
                }

                //获取当前机器制造的最晚时间
                Date maxEndTime = hcPlanMakePartExampleMapper.getMaxEndTime(make_machine);

                //获取选择的这一批订单他们的最早的那个总装的开始时间
                Date minAssemblyStartDate = hcPlanFinalAssemblyMapper.getMinAssemblyStartDate(assemblyIds);

                if (minAssemblyStartDate == null){
                    throw new AdscmSystemException("没有找到总装的时间");
                }

                Integer productionTime = hcPlanMakePartMapper.getProductionTime();//每天的标准生产时间

                float md_1 =  cycle_hour % productionTime.floatValue();
                float md = 0;
                if(cycle_hour % productionTime == 0){
                    md = -1;
                }
                md += cycle_hour / productionTime;
                if (md_1 > 0){
                    md += 1;
                }

                //结束时间
                if(maxEndTime == null){
                    //当前时间的明天
                    startDate = AdscmDateUtils.getThatDate(new Date(),1,Calendar.DATE);
                }else {
                    //机器最后一天时间的明天
                    startDate = AdscmDateUtils.getThatDate(maxEndTime,1,Calendar.DATE);
                }
                endDate = AdscmDateUtils.getThatDate(startDate,(int)md,Calendar.DATE);

                //将生产耗时，单位改为 天，保留两位小数
                float cycle_day = 0f;//耗时，天
                cycle_day = (cycle_hour / productionTime + 0.005f);
                cycle_day = (Math.round(cycle_day*100f)/100f);

                map.put("cycle_hour",cycle_hour);
                map.put("cycle_day",cycle_day);
                map.put("make_machine",make_machine);
                map.put("make_total_num",make_total_num);
                map.put("startDate",startDate);
                map.put("endDate",endDate);

                return map;
            }else {
                throw new AdscmSystemException("没有接收到参数 ids ；");
            }
        }catch (Exception e){
            logger.error("程序自动计算，选择的一批待并单的零件的 生产时间异常",e);
            throw new AdscmSystemException(e.getMessage());
        }
    }

    @Override
    public Map<String, Object> calculateMakePartTime(Long[] ids) throws AdscmSystemException {
        logger.info("程序自动计算，选择的一批待并单的零件的 生产时间...");
        try{
            Map<String, Object> map = new HashMap<>();
            if (ids != null && ids.length >0 ){
                List<HcPlanMakePartExample> examples = hcPlanMakePartExampleMapper.selectBatchIds(Arrays.asList(ids));//所有选择的待并单的零件

                Float cycle_hour = 0f;//花费时间
                String make_machine = null;//制造机器
                Float make_total_num = 0f;//制造总数

                Date startDate = null;//开始时间
                Date endDate = null;//结束时间

                List<Long> assemblyIds = new ArrayList<>();//所有总装ID集合

                for (HcPlanMakePartExample pe :
                        examples) {
                    if (make_machine == null){
                        make_machine = pe.getMake_machine();
                    }
                    cycle_hour += pe.getMake_cycle_hour();
                    make_total_num += pe.getMake_total_num();

                    assemblyIds.add(pe.getAssembly_id());
                }

                //获取当前机器制造的最晚时间
                Date maxEndTime = hcPlanMakePartExampleMapper.getMaxEndTime(make_machine);

                //获取选择的这一批订单他们的最早的那个总装的开始时间
                Date minAssemblyStartDate = hcPlanFinalAssemblyMapper.getMinAssemblyStartDate(assemblyIds);

                if (minAssemblyStartDate == null){
                    throw new AdscmSystemException("没有找到总装的时间");
                }

                Integer productionTime = hcPlanMakePartMapper.getProductionTime();//每天的标准生产时间

                float md_1 =  cycle_hour % productionTime.floatValue();
                float md = 0;
                if(cycle_hour % productionTime == 0){
                    md = -1;
                }
                md += cycle_hour / productionTime;
                if (md_1 > 0){
                    md += 1;
                }

                //结束时间
                if(maxEndTime == null){
//                    endDate = AdscmDateUtils.getThatDate(minAssemblyStartDate,-1,Calendar.DATE);
                    endDate = minAssemblyStartDate;

                    //如果没有机器生产的最后时间，就直接按照总装开始时间来计算
                    // (int)(md + 0.5) 表示在强转的时候四舍五入
                    startDate = AdscmDateUtils.getThatDate(endDate,AdscmBaseUtils.getInstance().getOppositeNum((int)md),Calendar.DATE);

                }else {

                    //有机器生产的最后时间和总装的最开始时间，那么就最好是选择总装开始前和机器安装后，如果不能满足机器安装后，则优先满足总装前。


                    if (maxEndTime.getTime() < minAssemblyStartDate.getTime()){
//                        endDate = AdscmDateUtils.getThatDate(maxEndTime,-1,Calendar.DATE);

                        Date temp = AdscmDateUtils.getThatDate(minAssemblyStartDate,AdscmBaseUtils.getInstance().getOppositeNum((int)md),Calendar.DATE);
                        if (maxEndTime.getTime() < temp.getTime()){
                            startDate = maxEndTime;//AdscmDateUtils.getThatDate(maxEndTime,1,Calendar.DATE);
                            endDate = AdscmDateUtils.getThatDate(startDate,(int)md,Calendar.DATE);
                        }else {
                            //优先保证总装前

                            //看这几个被选择的待并单的，他们的这个机器的最早生产时间，如果有，则按照这个时间往前推，如果没有，则按照总装时间往前推
                            //获取这几个总装当前机器制造的最早时间
                            Date minStartTime = hcPlanMakePartExampleMapper.getMinStartTime(make_machine,assemblyIds);
                            if (minStartTime != null && minStartTime.getTime() < minAssemblyStartDate.getTime()){
                                endDate = minStartTime;
                            }else {
                                endDate = minAssemblyStartDate;
                            }

                            startDate = AdscmDateUtils.getThatDate(endDate,AdscmBaseUtils.getInstance().getOppositeNum((int)md),Calendar.DATE);
                        }

                    }else {
                        //优先保证总装前

                        //看这几个被选择的待并单的，他们的这个机器的最早生产时间，如果有，则按照这个时间往前推，如果没有，则按照总装时间往前推
                        //获取这几个总装当前机器制造的最早时间
                        Date minStartTime = hcPlanMakePartExampleMapper.getMinStartTime(make_machine,assemblyIds);
                        if (minStartTime != null && minStartTime.getTime() < minAssemblyStartDate.getTime()){
                            endDate = minStartTime;
                        }else {
                            endDate = minAssemblyStartDate;
                        }
                        startDate = AdscmDateUtils.getThatDate(endDate,AdscmBaseUtils.getInstance().getOppositeNum((int)md),Calendar.DATE);
                    }
                }

                map.put("cycle_hour",cycle_hour);
                map.put("make_machine",make_machine);
                map.put("make_total_num",make_total_num);
                map.put("startDate",startDate);
                map.put("endDate",endDate);


                return map;
            }else {
                throw new AdscmSystemException("没有接收到参数 ids ；");
            }
        }catch (Exception e){
            logger.error("程序自动计算，选择的一批待并单的零件的 生产时间异常",e);
            throw new AdscmSystemException(e.getMessage());
        }
    }
}
